package cn.shop.front.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : 李一涵
 * @date : Created in 2022-7-12 13:44
 * @description :
 */
@Aspect
@Slf4j
@Component
@Order(1)
public class WatchRunTimeAop {

    @Pointcut("execution(public * cn.shop.front.controller.*.*(..))")
    public void watchTime() {

    }

    @Around(value = "watchTime()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return pjp.proceed();
        }
        long uid = 0L;
        if (StpUtil.isLogin()) {
            uid = StpUtil.getLoginIdAsLong();
        }
        HttpServletRequest request = attributes.getRequest();
        String urlStr = request.getRequestURL().toString();
        StopWatch watch = new StopWatch();
        watch.start(URLUtil.getPath(urlStr));
        Object result = pjp.proceed();
        watch.stop();
        log.info("耗时监控: 用户 {} 请求 {} 耗时时间 {} 秒", uid, watch.getLastTaskName(), watch.getTotalTimeSeconds());
        return result;
    }
}